#!/usr/bin/env node
/**
 * 日志清理脚本
 * 清除项目中的非报错调试日志
 */

const fs = require('fs');
const path = require('path');

// 需要清理的文件类型
const FILE_EXTENSIONS = ['.js', '.vue'];

// 需要清理的目录
const DIRECTORIES = [
  'src/components',
  'src/utils',
  'src/store'
];

// 要保留的日志类型（错误日志）
const KEEP_PATTERNS = [
  /config\.logger\.error/,
  /this\.\$config\.logger\.error/,
  /console\.error.*(?:错误|失败|异常|Error)/i
];

// 要清理的日志模式
const CLEANUP_PATTERNS = [
  /console\.log\(/g,
  /console\.info\(/g,
  /console\.warn\(/g,
  /console\.debug\(/g,
  // 保留已经转换的config.logger调用，但移除多余的调试信息
];

function shouldKeepLine(line) {
  // 保留错误日志
  return KEEP_PATTERNS.some(pattern => pattern.test(line));
}

function cleanupFile(filePath) {
  try {
    const content = fs.readFileSync(filePath, 'utf8');
    const lines = content.split('\n');
    
    let modified = false;
    const cleanedLines = lines.filter(line => {
      // 如果是需要保留的日志行，保留
      if (shouldKeepLine(line)) {
        return true;
      }
      
      // 检查是否包含要清理的模式
      const hasCleanupPattern = CLEANUP_PATTERNS.some(pattern => pattern.test(line));
      
      if (hasCleanupPattern) {
        console.log(`清理: ${filePath} - ${line.trim()}`);
        modified = true;
        return false;
      }
      
      return true;
    });
    
    if (modified) {
      fs.writeFileSync(filePath, cleanedLines.join('\n'));
      console.log(`✅ 已清理文件: ${filePath}`);
    }
    
  } catch (error) {
    console.error(`❌ 清理文件失败 ${filePath}:`, error.message);
  }
}

function walkDirectory(dir) {
  try {
    const items = fs.readdirSync(dir);
    
    items.forEach(item => {
      const fullPath = path.join(dir, item);
      const stat = fs.statSync(fullPath);
      
      if (stat.isDirectory()) {
        walkDirectory(fullPath);
      } else if (stat.isFile()) {
        const ext = path.extname(fullPath);
        if (FILE_EXTENSIONS.includes(ext)) {
          cleanupFile(fullPath);
        }
      }
    });
  } catch (error) {
    console.error(`❌ 遍历目录失败 ${dir}:`, error.message);
  }
}

console.log('🧹 开始清理项目日志...');

DIRECTORIES.forEach(dir => {
  const fullPath = path.resolve(dir);
  if (fs.existsSync(fullPath)) {
    console.log(`📁 清理目录: ${dir}`);
    walkDirectory(fullPath);
  } else {
    console.log(`⚠️  目录不存在: ${dir}`);
  }
});

console.log('✨ 日志清理完成！');